package com.fengmi.interceptor;

import cn.hutool.json.JSONUtil;
import com.fengmi.entity.sso.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    private static ThreadLocal<SysUser> local = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取用户信息
        String userInfo = request.getHeader("userInfo");
        SysUser sysUser = JSONUtil.toBean(userInfo, SysUser.class);
        if(sysUser != null){
            local.set(sysUser);
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        local.remove();
    }

    public static SysUser getUserInfo(){
        return local.get();
    }
}
